package com.wholesmart.common.security.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.wholesmart.common.security.crypto.Crypto;
import com.wholesmart.common.security.properties.BrowserSecurityProperties;
/**
 * 解密登录请求中的密码，该过滤器在org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter前
 * 
 * @author dyw
 * @date 2019年12月16日
 */
@Component
public class DecodePasswordFilter implements Filter {
	@Autowired
	private BrowserSecurityProperties browserSecurityProperties;
	@Autowired(required = false)
	private Crypto cryptoInterface;
	public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
	private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		if (StringUtils.endsWithIgnoreCase(httpRequest.getRequestURI(),
				browserSecurityProperties.getLoginProcessingUrl())) {// 如果是登录路径
			if (browserSecurityProperties.getPasswordDecode() != null) {// 如果需要解密
				CustomHttpServletRequestWrapper requestWrapper = new CustomHttpServletRequestWrapper(httpRequest);
				String password = requestWrapper.getParameter(passwordParameter);
				if (password == null) {
					password = "";
				}
				password = password.trim();
				String depassword = cryptoInterface.decode(password);
				requestWrapper.setParameter(passwordParameter, depassword.trim());
				chain.doFilter(requestWrapper, response);
			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}
	}
}
